class DailyController < ApplicationController

  #在刷新dailyList页面的之前，准备以下数据发送至前台
  def dailyList
    if(Daily.findLastedDate)
      date = Daily.findLastedDate.date
    else
      date = '没有日报记录'
    end
    @lastedDate = date.to_s                                                     #被自动塞进了dailyList.html.erb文件中。其他的controller不能如此使用
  end

  #根据日期获取日报列表，如果没有日期限制，就选择最新的日期
  def getDailies
    if params[:date]!=nil&&params[:date]!=''                                    #如果有日期的限制条件
      total = Daily.countByDate params[:date]
      #      dailies = Daily.findPageByDate params[:date],params[:start].to_i,params[:limit].to_i
      dailies = Daily.findByDate params[:date]
    elsif Daily.findLastedDate                                                  #如果有日期的限制条件
      date = Daily.findLastedDate.date
      total = Daily.countByDate date
      #      dailies = Daily.findPageByDate date,params[:start].to_i,params[:limit].to_i
      dailies = Daily.findByDate date
    else                                                                        #如果没有日期限制条件，就选择最近的日期来显示
      date = '没有日报记录'
      total = 0
      dailies = 0
    end
    jsonStr="{root:"+dailies.to_json(:include => :train)+",total:"+total.to_s+"}"
    render :text => jsonStr,:layout => false
  end

  def getDates
    dates = Daily.findDistinctDate
    jsonStr = "{root:"+dates.to_json()+",total:"+dates.length.to_s+"}"
    jsonStr = jsonStr.gsub(/\//,"-")                                            #将'\'替换成为'-'
    render :text => jsonStr,:layout => false
  end

  #  def create
  #    begin
  #      daily = Daily.findByTrainIdAndDate params[:train_id] ,params[:date]
  #      if daily != nil
  #        info = '日报项已存在，请检查数据！'
  #      else
  #        newDaily = Daily.new                                                    #新建一条维护记录
  #        newDaily.all_length = params[:all_length]
  #        newDaily.last_length = params[:last_length]
  #        newDaily.now_length = params[:now_length]
  #        newDaily.xx_length = params[:xx_length]
  #        newDaily.ts_length = params[:ts_length]
  #        newDaily.threex_length = params[:threex_length]
  #        newDaily.fourx_length = params[:fourx_length]
  #        newDaily.date = params[:date]
  #        newDaily.train_id = params[:train_id]
  #        newDaily.save!
  #        info = 'success'
  #      end
  #    rescue Exception => e
  #      info = e.to_s
  #    end
  #    result = "{success:true,info:\"#{info}\"}"
  #    render :text => result,:layout => false
  #  end

  def delete
    begin
      ids= params[:id][1..params[:id].length-2].split(',')
      Daily.destroy(ids)
      info = 'success'
      lastedDate = (Daily.findLastedDate ? Daily.findLastedDate.date.to_s : '没有日报记录')
    rescue Exception=>e
      logger.info e
      info = '删除日报'
    end
    result = "{success:true,info:\"#{info}\",lastedDate:\"#{lastedDate}\"}"
    render :text=>result, :layout=>false
  end

  def deleteAll
    begin
      if params[:date]!=nil&&params[:date]!=''                                    #如果有日期的限制条件
        dailies = Daily.findByDate params[:date]
        for daily in dailies
          daily.destroy
        end
        info = 'success'
      else                                                                        #如果没有日期限制条件，就选择最近的日期来显示
        info = '请设置日报日期，之后选择删除'
      end
      lastedDate = (Daily.findLastedDate ? Daily.findLastedDate.date.to_s : '没有日报记录')
    rescue Exception=>e
      logger.info e
      info = '删除异常'
    end
    result = "{success:true,info:\"#{info}\",lastedDate:\"#{lastedDate}\"}"
    render :text=>result, :layout=>false
  end

  def edit
    daily = Daily.find(params[:dailyId])
    render :text=>daily.to_json(),:layout=>false
  end

  def update
    begin
      newDaily = Daily.find(params[:id])
      newDaily.all_length = params[:all_length]
      newDaily.last_length = params[:last_length]
      newDaily.now_length = params[:now_length]
      newDaily.xx_length = params[:xx_length]
      newDaily.ts_length = params[:ts_length]
      newDaily.two_level_fix_length = params[:two_level_fix_length]
      newDaily.threex_length = params[:threex_length]
      newDaily.fourx_length = params[:fourx_length]
      newDaily.save!
      info = 'success'
    rescue Exception=>e
      logger.info e
      info = '更新异常'
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end

  #根据车辆上带有的日期信息，判断当前应该的公里数
  def generateDailies
    begin
      if Daily.findLastedDate                                                     #如果存在最新时间
        lastedDate = Daily.findLastedDate.date                                    #得到列表中最新的日期
      else                                                                        #否则
        lastedDate = Time.mktime(2000)                                            #随便造一个过去的时间
      end
      nowDate = Time.now.to_date                                                  #得到当前日期
      if lastedDate >= nowDate                                                    #如果日报的最新时间比当前时间要新
        info = '您已经生成过更新的日报，不能重复生成！'                                  #那么就不要生成日报
      else

        #trains = Train.find :all                                                #得到所有列车数据
        #只查询非锁定的列车。
        trains = Train.where("is_locked = 0")
        nowDate = Time.now.to_date                                              #得到当前日期
        for train in trains                                                     #遍历列车列表
          #将新的数据写到日报中
          newDaily = Daily.new                                                  #新建一条维护记录
          newDaily.sn = train.sn                                                #把列车的编号存入日报
          newDaily.date = nowDate
          newDaily.train_id = train.id                                          #将日报与列车对象关联
          if(train.router_date)                                                 #如果有交路设置日期，就说明其交路已经设置
            #以下：计算当前的交路长度
            sequence = ((nowDate - train.router_date) % train.router_number).to_i    #（当前时间-交路设置时间），和交路数取余，即可得到交路编号
            router = TrainRouter.findByTrainIdAndSequence(train.id,sequence).router  #通过列车id和队列得到交路对象
            nowLength = router.length                                           #本次走行
            #以上
            #以下：计算交路在时间段内所跑的长度
            routerTimes = ((nowDate - train.router_date - 1) / train.router_number).to_i  #交路循环次数
            lengths = 0                                                         #交路在时间段内所跑的长度（偏移量）
            i = 1                                                               #计数器
            loop do                                                             #计算一个循环圈的总长度
              sequence = i - 1
              length = TrainRouter.findByTrainIdAndSequence(train.id,sequence).router.length
              lengths += length
              i += 1
              break if i > train.router_number
            end
            lengths = lengths * routerTimes                                     #得到所有循环圈的总长度
            i = 0
            remainderTimes = ((nowDate - train.router_date - 1) % train.router_number).to_i
            loop do                                                             #计算余数的总长度
              sequence = i
              length = TrainRouter.findByTrainIdAndSequence(train.id,sequence).router.length
              lengths += length
              i += 1
              break if i > remainderTimes
            end
            #以上
            newDaily.train_number = router.train_number                         #赋值给日报
            newDaily.line = router.line                                         #赋值给日报
            newDaily.length = nowLength                                         #一次走行公里
          else                                                                  #如果没设置日期，说明未设置交路
            nowLength = 0                                                       #本次走行
            lastLength = 0                                                      #上次走行
            lengths = 0                                                         #没有交路说明走行距离为0
            newDaily.train_number = '未设置'                                     #赋值给日报
            newDaily.line = '未设置'                                             #赋值给日报
            newDaily.length = 0                                                 #赋值给日报
          end
          newDaily.last_length = train.all_length.to_i + lengths - nowLength         #上次走行长度
          newDaily.now_length = train.all_length.to_i + lengths                      #本次走行长度
          newDaily.all_length = train.all_length.to_i + lengths                      #旧的长度加上偏移长度等于新的长度
          if train.xx_length                                                    #如果镟修后走行数不为空
            newDaily.xx_length = train.xx_length + lengths                      #镟修后走行数进行增加
          end                                                                   #如果为空，就不增加
          if train.ts_length
            newDaily.ts_length = train.ts_length + lengths
          end
          if train.two_level_fix_length
            newDaily.two_level_fix_length = train.two_level_fix_length + lengths
          end
          if train.threex_length
            newDaily.threex_length = train.threex_length + lengths
          end
          if train.fourx_length
            newDaily.fourx_length = train.fourx_length + lengths
          end
          newDaily.save!
          
          #将新的数据写到列车上，如果不用写到列车上，则直接注释掉以下代码即可
          train.last_length = train.all_length + lengths - nowLength            #上次走行长度
          train.now_length = train.all_length + lengths                         #本次走行长度
          train.all_length = train.all_length + lengths                         #旧的长度加上偏移长度等于新的长度
          if train.xx_length                                                    #如果镟修后走行数不为空
            train.xx_length = train.xx_length + lengths                         #镟修后走行数进行增加
          end                                                                   #如果为空，就不增加
          if train.ts_length
            train.ts_length = train.ts_length + lengths
          end
          if train.threex_length
            train.threex_length = train.threex_length + lengths
          end
          if train.fourx_length
            train.fourx_length = train.fourx_length + lengths
          end
          train.date = nowDate
          train.save!
        end
        lastedDate = Daily.findLastedDate.date.to_s                             #将最新事件作为参数传到前台
        info = 'success'

      end

    rescue Exception => e
      info = e.to_s
      logger.info info
      DbLog.info( params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    
    result = "{success:true,info:\"#{info}\",lastedDate:\"#{lastedDate}\"}"
    render :text=>result, :layout=>false
  end

  def xx                                                                        #镟修功能，将镟修长度设为0
    daily = Daily.find(params[:trainId])
    daily.xx_length = 0                                                         #将日报上的镟修后长度设为0
    daily.save!
    trainId = daily.train_id
    train = Train.find(trainId)
    train.xx_length = 0                                                         #将列车上的镟修后长度设为0
    train.save!
    info = 'success'
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end

  def ts                                                                        #探伤功能，将探伤长度设为0
    daily = Daily.find(params[:trainId])
    daily.ts_length = 0
    daily.save!
    trainId = daily.train_id
    train = Train.find(trainId)
    train.ts_length = 0                                                         #将列车上的镟修后长度设为0
    train.save!
    info = 'success'
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end

  def threex                                                                    #三级修功能，将三级修长度设为0
    daily = Daily.find(params[:id])
    daily.threex_length = 0
    daily.save!
    trainId = daily.train_id
    train = Train.find(trainId)
    train.threex_length = 0                                                     #将列车上的镟修后长度设为0
    train.save!
    info = 'success'
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end

  def fourx                                                                     #四级修功能，将四级修长度设为0
    daily = Daily.find(params[:id])
    daily.fourx_length = 0
    daily.save!
    trainId = daily.train_id
    train = Train.find(trainId)
    train.fourx_length = 0                                                      #将列车上的镟修后长度设为0
    train.save!
    info = 'success'
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end

  #打印维修单
  require "spreadsheet"
  def printDailyList
    Spreadsheet.client_encoding = "UTF-8"
    bookString = StringIO.new
    book = Spreadsheet.open "#{Rails.root.to_s}/public/report_template/dailyListReport.xls"
    date = params[:date]
    dailies = Daily.findAllByDate(date)
    sheet1 = book.worksheet 0
    sheet1[1,0] = '日期：'+ date[0,4]+'年'+date[5,2]+'月'+date[8,2]+'日'          #先竖后横，起始值从0开始
    timer = 3                                                                   #excel中，从第三个开始是第一条记录
    for daily in dailies
      sheet1[timer,1] = daily.sn
      sheet1[timer,2] = daily.train_number
      sheet1[timer,3] = daily.line
      sheet1[timer,11] = daily.length
      sheet1[timer,4] = daily.last_length
      sheet1[timer,5] = daily.now_length
      sheet1[timer,6] = daily.all_length
      sheet1[timer,7] = daily.xx_length
      sheet1[timer,8] = daily.ts_length
      sheet1[timer,9] = daily.threex_length
      sheet1[timer,10] = daily.fourx_length

      timer = timer + 1
    end
    
    timer = 0
    sheet1.each do |row|
      timer = timer + 1
    end
    book.write bookString
    send_data(bookString.string, :type => "application/excel", :disposition => 'attachment', :filename => 'daily_report '+date+'.xls')
  end

end


